package server.load;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.mapper.MappedWrapper;
import server.servlet.impl.HttpServlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

public class LoadServlet {

    /**
     * 加载解析Web.xml,初始化Servlet
     * @param path 类所在路径
     * @param fileInputStream 读取的web.xml 流
     *
     * @return
     */
    public List<MappedWrapper> load(String path, FileInputStream fileInputStream) {
        SAXReader saxReader = new SAXReader();
        List<MappedWrapper> mappedWrapperList = new ArrayList<>();
        try {
            Document document = saxReader.read(fileInputStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            MyClassLoader myClassLoader = new MyClassLoader();
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                //<servlet-name>jiancong</servlet-name>
                Element servletNameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletNameElement.getStringValue();

                //<servlet-class>server.servlet.impl.ChenServlet</servlet-class>
                Element servletClassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletClassElement.getStringValue();

                //根据Servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                //<url-pattern>/jiancong</url-pattern>
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                //根据项目所在路径，加载servlet类
                URL classUrl = new File(path).toURI().toURL();
                URLClassLoader classLoader = new URLClassLoader(new URL[]{classUrl});
                //Class<?> aClass = classLoader.loadClass(servletClass);
                Class<?> aClass = myClassLoader.findClass(path.replace("/", "\\")  + "\\",servletClass);

                //存储路径和Servlet的映射关系
                MappedWrapper mappedWrapper = new MappedWrapper(urlPattern, (HttpServlet) aClass.getDeclaredConstructor().newInstance());
                mappedWrapperList.add(mappedWrapper);
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return mappedWrapperList;
    }
}
